package user

import (
	"sanguo/node/common/transaction"
	//"sanguo/node/node_game"
	"fmt"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionFinalSave struct {
	transaction.TransactionBase
	user     *User
	err      error
	callback func(error)
}

func (this *transactionFinalSave) GetModuleName() string {
	return "finalSave"
}

func (this *transactionFinalSave) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionFinalSave) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionFinalSave) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionFinalSave) Begin() {
	r := this.user.GetModuleByName("role")
	if nil != r {

		r.(interface {
			OnLogout()
		}).OnLogout()

		//上报最大等级
		r.(interface {
			ReportMaxLev()
		}).ReportMaxLev()

		r.(interface {
			ClearMap()
		}).ClearMap()

		r.(interface {
			ClearInstanceZone()
		}).ClearInstanceZone()

		r.(interface {
			Save(func(error))
		}).Save(func(err error) {
			if nil == err {
				if this.user.CheckTrans(this) {
					this.user.EndTrans(this)
				}
			} else {
				if this.user.CheckTrans(this) {
					this.onError(err)
				}
			}
		})
	}
}

func (this *transactionFinalSave) onError(err error) {
	this.err = err
	this.user.EndTrans(this)
}

func (this *transactionFinalSave) End() {
	if nil != this.callback {
		this.callback(this.err)
	}
}

func (this *transactionFinalSave) Timeout() {
	this.err = fmt.Errorf("timeout")
	this.user.EndTrans(this)
}

func (this *User) finalSave(callback func(error)) {

	trans := &transactionFinalSave{
		user:     this,
		callback: callback,
	}

	this.transMgr.PushTrans(trans, time.Second*transaction.TransTimeoutSec)
}
